package com.homedo.microservice.open.service.gateway.manager.web.autoconfig;

import com.netflix.turbine.discovery.InstanceDiscovery;
import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory;
import com.netflix.turbine.streaming.servlet.TurbineStreamServlet;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.actuator.HasFeatures;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.turbine.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties
public class LocalTurbineHttpConfiguration {

    @Bean
    public HasFeatures Feature() {
        return HasFeatures.namedFeature("Turbine (HTTP)", LocalTurbineHttpConfiguration.class);
    }

    @Bean
    @ConditionalOnMissingBean(name = "turbineStreamServlet")
    public ServletRegistrationBean turbineStreamServlet() {
        return new ServletRegistrationBean(new TurbineStreamServlet(), "/turbine.stream");
    }

    @Bean
    @ConditionalOnMissingBean
    public TurbineProperties turbineProperties() {
        return new TurbineProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    public TurbineAggregatorProperties turbineAggregatorProperties() {
        return new TurbineAggregatorProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    public TurbineLifecycle turbineLifecycle(InstanceDiscovery instanceDiscovery,
                                             ClusterMonitorFactory<?> factory) {
        return new TurbineLifecycle(instanceDiscovery, factory);
    }

    @Bean
    @ConditionalOnMissingBean
    public ClusterMonitorFactory clusterMonitorFactory(TurbineClustersProvider clustersProvider) {
        return new SpringAggregatorFactory(clustersProvider);
    }

    @Bean
    @ConditionalOnMissingBean
    public TurbineClustersProvider clustersProvider(TurbineAggregatorProperties turbineAggregatorProperties) {
        return new ConfigurationBasedTurbineClustersProvider(turbineAggregatorProperties);
    }

    @Configuration
//    @ConditionalOnMissingClass("com.netflix.discovery.EurekaClient")
    protected static class DiscoveryClientTurbineConfiguration {

        @Bean
        @ConditionalOnMissingBean
        public InstanceDiscovery instanceDiscovery(TurbineProperties turbineProperties, DiscoveryClient discoveryClient) {
//            return new CommonsInstanceDiscovery(turbineProperties, discoveryClient);
            return new LocalConfigPropertyBasedDiscovery();
        }
    }
}
